package danny.hoi.controller;

import com.github.pagehelper.PageInfo;
import danny.hoi.pojo.Result;
import danny.hoi.pojo.TbArticle;
import danny.hoi.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RequestMapping("/article")
@RestController
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    /**
     * 分页查询
     * @param pageNum   当前页
     * @param pageSize  页大小
     * @param article
     * @return
     */
    @PostMapping("/search")
    public PageInfo<TbArticle> search(@RequestParam(defaultValue = "1") Integer pageNum,
                                      @RequestParam(defaultValue = "10") Integer pageSize,
                                      @RequestBody TbArticle article){
        return articleService.search(pageNum,pageSize,article);
    }

    /**
     * 保存文章
     * @param article
     * @return
     */
    @PostMapping("/save")
    public Result save(@RequestBody TbArticle article){
        try {
            articleService.add(article);
            return Result.ok("添加成功了！");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.fail("添加失败了！");
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @GetMapping("/deleteArticle")
    public Result deleteArticle(Integer id) {
        try {
            articleService.delete(id);
            return Result.ok("删除成功了！");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.fail("删除失败了! ");
    }


    /**
     * 根据id查找
     * @param id
     * @return
     */
    @GetMapping("/findOne/{id}")
    public TbArticle findOne(@PathVariable Integer id){
        return articleService.findOne(id);
    }

    /**
     *更新
     * @param article
     * @return
     */
    @PostMapping("/update")
    public Result update(@RequestBody TbArticle article){
        try {
            articleService.update(article);
            return Result.ok("修改成功了！");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.fail("修改失败了！");
    }
}
